//
//  HMNavigationController.swift
//  WeiBo
//
//  Created by Apple on 2017/5/30.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit

//  自定义导航控制器
class HMNavigationController: UINavigationController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        //  设置返回手势代理
        self.interactivePopGestureRecognizer?.delegate = self

    }
    //  拦截push操作
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if viewControllers.count > 0 {
            //  隐藏tabbar， 注意加上这句代码导航栏会变黑，设置tabbar的背景图片或者设置window的颜色
            viewController.hidesBottomBarWhenPushed = true
        }
        
        super.pushViewController(viewController, animated: animated)
        if viewControllers.count == 2 {
            //  获取第一级控制器
            let vc = viewControllers.first!
            //  获取该控制器的标题
            let title = vc.title!
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
        } else {
            //  注意判断如果是根视图控制器不能添加返回
            if viewControllers.count > 2 {
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            }
            
        }
    }
    
    @objc private func backAction() {
        self.popViewController(animated: true)
    }

    //  MARK:   --UIGestureRecognizerDelegate
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        //  根视图不需要开启边缘返回手势
        if viewControllers.count == 1 {
            return false
        }
        return true
    }

}
